from django import forms

from oracle.models import OUserInfo
from oracle.base.basemodel import Status

# 错误信息
ERROR_MESSAGE = {
    'duplicate_username': "此用户已存在.",
    'password_mismatch': "两次密码不相等.",
    'duplicate_email': '此email已经存在.'
}


class UserCreateForm(forms.ModelForm):
    name = forms.RegexField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'placeholder': 'USERNAME'}),
        max_length=30,
        regex=r'^[\w.@+-]+$',
        strip=True,
        label="用户名",
        error_messages={
            'invalid': "该值只能包含字母、数字和字符@/./+/-/_",
            'required': "用户名未填",
        }
    )
    email = forms.EmailField(
        required=True,
        label="邮箱",
        widget=forms.widgets.EmailInput(attrs={'placeholder': 'EMAIL ADDRESS'}),
        error_messages={
            'invalid': "email格式错误",
            'required': 'email未填'}
    )
    password = forms.CharField(
        required=True,
        widget=forms.widgets.PasswordInput(attrs={'placeholder': 'PASSWORD'}),
        strip=True,
        label="密码",
        error_messages={
            'required': "密码未填"
        }
    )
    password_confirm = forms.CharField(
        required=True,
        widget=forms.widgets.PasswordInput(attrs={'placeholder': 'REPASSWORD'}),
        strip=True,
        label="确认密码",
        error_messages={
            'required': "确认密码未填"
        }
    )
    status = forms.ChoiceField(
        choices=Status.choices,
        widget=forms.widgets.Select(),
        label="状态",
        # initial=2,
    )
    level = forms.IntegerField(
        widget=forms.widgets.NumberInput(),
        label="等级",
        initial=0,
    )

    class Meta:
        model = OUserInfo
        fields = ("name", "password", "password_confirm", "email", "status", "level")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

    def clean_name(self):
        name = self.cleaned_data["name"]
        try:
            OUserInfo.objects.get(name=name)
        except OUserInfo.DoesNotExist:
            return name
        raise forms.ValidationError(
            ERROR_MESSAGE["duplicate_username"]
        )

    def clean_password_confirm(self):
        password = self.cleaned_data.get("password")
        password_confirm = self.cleaned_data.get("password_confirm")
        if password and password_confirm and password != password_confirm:
            raise forms.ValidationError(
                ERROR_MESSAGE["password_mismatch"]
            )
        return password_confirm

    def clean_email(self):
        email = self.cleaned_data["email"]

        # 判断是这个email 用户是否存在
        try:
            OUserInfo.objects.get(email=email)
        except OUserInfo.DoesNotExist:
            return email
        raise forms.ValidationError(
            ERROR_MESSAGE["duplicate_email"]
        )

    def _post_clean(self):
        super()._post_clean()

        for name, field in self.fields.items():
            if name in self.errors:
                field.widget.attrs['class'] = 'form-control error'


class UserUpdateForm(forms.ModelForm):
    name = forms.RegexField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'placeholder': 'USERNAME'}),
        max_length=30,
        regex=r'^[\w.@+-]+$',
        strip=True,
        label="用户名",
        error_messages={
            'invalid': "该值只能包含字母、数字和字符@/./+/-/_",
            'required': "用户名未填",
        }
    )
    email = forms.EmailField(
        required=True,
        label="邮箱",
        widget=forms.widgets.EmailInput(attrs={'placeholder': 'EMAIL ADDRESS'}),
        error_messages={
            'invalid': "email格式错误",
            'required': 'email未填',
        }
    )
    status = forms.ChoiceField(
        choices=Status.choices,
        widget=forms.widgets.Select(),
        label="状态",
        # initial=2,
    )
    level = forms.IntegerField(
        widget=forms.widgets.NumberInput(),
        label="等级",
        initial=0,
    )

    class Meta:
        model = OUserInfo
        fields = ("name", "email", "status", "level")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'


class UserPasswordResetForm(forms.ModelForm):
    password = forms.CharField(
        required=True,
        widget=forms.widgets.PasswordInput(attrs={'placeholder': 'PASSWORD'}),
        strip=True,
        label="密码",
        error_messages={
            'required': "密码未填"
        }
    )
    password_confirm = forms.CharField(
        required=True,
        widget=forms.widgets.PasswordInput(attrs={'placeholder': 'REPASSWORD'}),
        strip=True,
        label="确认密码",
        error_messages={
            'required': "确认密码未填"
        }
    )

    class Meta:
        model = OUserInfo
        fields = ("password", "password_confirm",)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

    def clean_password_confirm(self):
        password = self.cleaned_data.get("password")
        password_confirm = self.cleaned_data.get("password_confirm")
        if password and password_confirm and password != password_confirm:
            raise forms.ValidationError(
                ERROR_MESSAGE["password_mismatch"]
            )
        return password_confirm


class UserLoginForm(forms.Form):
    username = forms.CharField(
        label='Username',
        max_length=100,
        widget=forms.TextInput(attrs={
            "placeholder": "Username",
            "autofocus": "autofocus",
            "class": "form-control"
        })
    )
    password = forms.CharField(
        label='Password',
        max_length=1024,
        widget=forms.PasswordInput(attrs={
            "placeholder": "Password",
            "class": "form-control"
        }),
        strip=False
    )
